//
//  LLRefreshControl.swift
//  WeiBoShiBing
//
//  Created by Bingo on 15/11/3.
//  Copyright © 2015年 Bingo. All rights reserved.
//

import UIKit

class LLRefreshControl: UIRefreshControl {
    
    
    private let RefreshControlOffest:CGFloat = -60
    
    private var isUp = false
    
    override var frame:CGRect{
        didSet {
            if frame.origin.y >= 0{
                
                return
            }
            
            if refreshing {
                
                refreshView.startLoading()
            }
            
            if frame.origin.y < RefreshControlOffest && !isUp{
                print("箭头转上去")
                isUp = true
                
                refreshView.rotationTipViewIcon(isUp)
            
            }else if frame.origin.y > RefreshControlOffest && isUp{
                print("箭头转下去")
                isUp = false
                
                refreshView.rotationTipViewIcon(isUp)
            
            }
            
        }
    
    
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.stopLoading()
    }
    
    override init() {
        super.init()
        prepareUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func prepareUI(){
        addSubview(refreshView)
        
        print("refreshView\(refreshView)")
        
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
    
    }
    
    private lazy var refreshView:LLRefreshView = LLRefreshView.refreshView()
    

}

class LLRefreshView: UIView{
    
    
    @IBOutlet weak var loadingView:UIImageView!
    
    @IBOutlet weak var tipView:UIView!
    
    @IBOutlet weak var tipViewIcon:UIImageView!
    
    class func refreshView() -> LLRefreshView{
        return NSBundle.mainBundle().loadNibNamed("LLRefreshView", owner: nil, options: nil).last as! LLRefreshView
    
    }
    
    func rotationTipViewIcon(isup:Bool){
        UIView.animateWithDuration(0.25) { () -> Void in
            self.tipViewIcon.transform = isup ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.01)) : CGAffineTransformIdentity
            
        }
    
    }
    
    func startLoading(){
    
        let animKey = "animkey"
        
        if let _ = loadingView.layer.animationForKey(animKey){
            return
        }
        
        tipView.hidden = true
        
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = M_PI * 2
        anim.duration = 0.25
        anim.repeatCount = MAXFLOAT
        
        anim.removedOnCompletion = false
        
        loadingView.layer.addAnimation(anim, forKey: animKey)
        
    }
    
    func stopLoading(){
        tipView.hidden = false
        
        loadingView.layer.removeAllAnimations()
    
    }

}
